package com.adcc.loadsheet.billing.service.impl;

import com.adcc.loadsheet.billing.entity.chargerule.BillingLadderEntity;
import com.adcc.loadsheet.billing.entity.chargerule.BillingRuleEntity;
import com.adcc.loadsheet.billing.security.UserInfo;
import com.adcc.loadsheet.billing.service.BillingRuleService;
import com.adcc.loadsheet.billing.util.BillingTools;
import com.adcc.loadsheet.billing.util.DateTimeUtil;
import com.adcc.loadsheet.billing.util.LogUtil;
import com.adcc.loadsheet.billing.util.SystemOperationLogType;
import com.adcc.loadsheet.billing.vo.chargerule.BillingLadderEntityVO;
import com.adcc.loadsheet.billing.vo.chargerule.BillingRuleEntityVO;
import com.adcc.loadsheet.billing.vo.chargerule.BillingRuleTreeVO;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 计费规则表Service实现类
 * Created by zhaoml on 2020/4/7.
 */
@Service
public class BillingRuleServiceImpl extends BasisServiceImpl implements BillingRuleService {

    //获取计费规则Tree（按照规则简称升序排列）
    @Override
    public List<BillingRuleTreeVO> getTreeNode(){
        List<BillingRuleTreeVO> vos = Lists.newArrayList();

        //根节点
        BillingRuleTreeVO rootNode = new BillingRuleTreeVO("0","0","计费规则",true,true);
        vos.add(rootNode);

        Map<String, Object> map = Maps.newHashMap();
        //合同用户可以查询自己的计费规则，无修改权限且只能查看自己的计费规则
        if(!userContext.getCurrentUser().isSuperAdmin()){
            map.put("PB_LOGIN_ID",userContext.getCurrentUser().getUsername());
        }
        List<BillingRuleEntity> list = billingRuleEntityMapper.select(map);
        list.stream().forEach(entity -> vos.add(new BillingRuleTreeVO(entity,true,false)));

        return vos;
    }

    //查询手册计费规则，包括阶梯计数
    @Override
    public BillingRuleEntityVO findByBillingRuleId(Map<String, Object> paramMap){
        Integer billingRuleId = Integer.valueOf(paramMap.get("billingRuleId").toString());
        //查询计费规则
        BillingRuleEntity billingRuleEntity = billingRuleEntityMapper.selectByPrimaryKey(billingRuleId);
        //查询阶梯计数
        List<BillingLadderEntity> billingLadderEntityList = billingLadderEntityMapper.selectByBillingRuleId(billingRuleId);

        BillingRuleEntityVO vo = new BillingRuleEntityVO(billingRuleEntity,billingLadderEntityList);
        return vo;
    }

    //查询手册计费规则，不包括阶梯计数
    @Override
    public BillingRuleEntity findByBillingRuleId(Integer billingRuleId){
        BillingRuleEntity billingRuleEntity = billingRuleEntityMapper.selectByPrimaryKey(billingRuleId);
        return billingRuleEntity;
    }

    //根据规则简称查询对应实体
    @Override
    public BillingRuleEntity findByRuleAbbrev(String ruleAbbrev){
        return billingRuleEntityMapper.findByRuleAbbrev(ruleAbbrev);
    }

    //编辑计费规则（包括阶梯计数）
    @Override
    @Transactional(transactionManager = "mysqlTransactionManager")
    public BillingRuleEntity edit(BillingRuleEntityVO billingRuleEntityVO){
        String res = "";
        String logContent = "";     //日志内容
        try {
            BillingRuleEntity billingRuleEntity = billingRuleEntityVO.toEntity();
            UserInfo user = userContext.getCurrentUser();
            billingRuleEntity.setUpdateAt(DateTimeUtil.getNowDate());
            billingRuleEntity.setUpdateUser(user.getUsername());
            //保存计费规则
            if(billingRuleEntity.getBillingRuleId() == null){
                billingRuleEntity.setCreateAt(DateTimeUtil.getNowDate());
                billingRuleEntity.setCreateUser(user.getUsername());
                billingRuleEntityMapper.insert(billingRuleEntity);
                res = "新增成功";
                //记录操作日志
                LogUtil.operationLog(SystemOperationLogType.BillingRule_Operation.ordinal(), "新增计费规则“" + billingRuleEntityVO.getRuleAbbrev() + "”", user.getUsername());
            }else {
                //记录操作日志
                BillingRuleEntity oldBillingRuleEntity = billingRuleEntityMapper.selectByPrimaryKey(billingRuleEntity.getBillingRuleId());
                if(!oldBillingRuleEntity.getRuleAbbrev().equals(billingRuleEntity.getRuleAbbrev())){
                    logContent += Strings.isNullOrEmpty(logContent) ? "修改计费规则“" + oldBillingRuleEntity.getRuleAbbrev() + "”：" : "";
                    logContent += "规则简称由“" + oldBillingRuleEntity.getRuleAbbrev() + "”修改为“" + billingRuleEntity.getRuleAbbrev() + "”";
                }
                String oldRuleFullname = Strings.isNullOrEmpty(oldBillingRuleEntity.getRuleFullname()) ? "" : oldBillingRuleEntity.getRuleFullname();
                String newRuleFullname = Strings.isNullOrEmpty(billingRuleEntity.getRuleFullname()) ? "" : billingRuleEntity.getRuleFullname();
                if(!oldRuleFullname.equals(newRuleFullname)) {
                    logContent += Strings.isNullOrEmpty(logContent) ? "修改计费规则“" + oldBillingRuleEntity.getRuleAbbrev() + "”：规则全称由“" + oldRuleFullname + "”修改为“" + newRuleFullname + "”" : "，规则全称由“" + oldRuleFullname + "”修改为“" + newRuleFullname + "”";
                }
                String oldRemark = Strings.isNullOrEmpty(oldBillingRuleEntity.getRemark()) ? "" : oldBillingRuleEntity.getRemark();
                String newRemark = Strings.isNullOrEmpty(billingRuleEntity.getRemark()) ? "" : billingRuleEntity.getRemark();
                if(!oldRemark.equals(newRemark)) {
                    logContent += Strings.isNullOrEmpty(logContent) ? "修改计费规则“" + oldBillingRuleEntity.getRuleAbbrev() + "”：备注由“" + oldRemark + "”修改为“" + newRemark + "”" : "，备注由“" + oldRemark + "”修改为“" + newRemark + "”";
                }
                if(!Strings.isNullOrEmpty(logContent)){
                    LogUtil.operationLog(SystemOperationLogType.BillingRule_Operation.ordinal(), logContent, user.getUsername());
                }

                billingRuleEntityMapper.update(billingRuleEntity);
                res = "编辑成功";
            }

            //保存阶梯计数，删除后再存（先记录操作日志）
            List<BillingLadderEntity> oldBillingLadderEntityList = billingLadderEntityMapper.selectByBillingRuleId(billingRuleEntity.getBillingRuleId());//已有的阶梯计数
            List<BillingLadderEntity> newBillingLadderEntityList = Lists.newArrayList();    //新的阶梯计数
            List<String> oldBillingLadderList = Lists.newArrayList();   //编辑已有的阶梯计数，格式：开始计数-结束计数=单价
            List<String> newBillingLadderList = Lists.newArrayList();   //编辑新的阶梯计数，格式：开始计数-结束计数=单价

            BillingLadderEntity oldBillingLadderEntity;
            for(int i = 0;i < oldBillingLadderEntityList.size();i ++){
                oldBillingLadderEntity = oldBillingLadderEntityList.get(i);
                oldBillingLadderList.add(oldBillingLadderEntity.getLadderStartnumber() + "-" + oldBillingLadderEntity.getLadderEndnumber() + "=" + oldBillingLadderEntity.getUnitPrice() + "元");
            }
            BillingLadderEntityVO newLadderEntityVO;
            for(int j = 0;j < billingRuleEntityVO.getBillingLadderEntityVOList().size();j ++){
                newLadderEntityVO = billingRuleEntityVO.getBillingLadderEntityVOList().get(j);
                newBillingLadderList.add(newLadderEntityVO.getLadderStartnumber() + "-" + newLadderEntityVO.getLadderEndnumber() + "=" + newLadderEntityVO.getUnitPrice() + "元");
                //新的计费阶梯列表
                newLadderEntityVO.setBillingRuleId(billingRuleEntity.getBillingRuleId());
                BillingLadderEntity ladderEntity = newLadderEntityVO.toEntity();
                newBillingLadderEntityList.add(ladderEntity);
            }
            //获取差别
            Map<String,String> map = BillingTools.getDifference(oldBillingLadderList, newBillingLadderList);
            String less = map.get("less").toString();
            String more = map.get("more").toString();
            logContent = "";
            if(!Strings.isNullOrEmpty(less)){
                logContent = "修改计费规则“" + billingRuleEntity.getRuleAbbrev() + "”：删除计费阶梯（" + less.replace(",","、") + "）";
            }
            if(!Strings.isNullOrEmpty(more)){
                logContent += Strings.isNullOrEmpty(logContent) ? "修改计费规则“" + billingRuleEntity.getRuleAbbrev() + "”：增加计费阶梯（" + more.replace(",","、") + "）" : "，增加计费阶梯（" + more.replace(",","、") + "）";
            }
            if(!Strings.isNullOrEmpty(logContent)){
                LogUtil.operationLog(SystemOperationLogType.BillingRule_Operation.ordinal(), logContent, user.getUsername());
            }

            billingLadderEntityMapper.deleteByBillingRuleId(billingRuleEntity.getBillingRuleId());
            //批量添加
            if(newBillingLadderEntityList != null && newBillingLadderEntityList.size() > 0){
                billingLadderEntityMapper.insertBatch(newBillingLadderEntityList);
            }

            return billingRuleEntity;
        }catch (Exception ex) {
            throw ex;
        }
    }

    //删除计费规则
    @Override
    @Transactional(transactionManager = "mysqlTransactionManager")
    public String deleteByBillingRuleId(Integer billingRuleId) {
        String res = "";
        try {
            //记录操作日志
            BillingRuleEntity billingRuleEntity = billingRuleEntityMapper.selectByPrimaryKey(billingRuleId);
            LogUtil.operationLog(SystemOperationLogType.BillingRule_Operation.ordinal(), "删除计费规则“" + billingRuleEntity.getRuleAbbrev() + "”", userContext.getCurrentUser().getUsername());

            //删计费阶梯
            billingLadderEntityMapper.deleteByBillingRuleId(billingRuleId);
            //删计费规则
            billingRuleEntityMapper.deleteByPrimaryKey(billingRuleId);
            res = "删除成功！";
            return res;
        } catch (Exception ex) {
            throw ex;
        }
    }
}